﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Controls.Primitives;

namespace produccion.forms
{
    /// <summary>
    /// Lógica de interacción para FrmRepNovedadConcepto.xaml
    /// </summary>
    public partial class FrmRepNovedadConcepto : Window
    {
        public FrmRepNovedadConcepto()
        {
            InitializeComponent();
        }

        private void ventana_Loaded(object sender, RoutedEventArgs e)
        {
            dtgNovedades.Style = null;//FJRF - Le quietamos el estilo al objeto para poder manipular el foco 

            txtSemana.Style = null;//FJRF - Le quietamos el estilo al objeto para poder manipular el foco 
            
            cmbProcesoCodigo.Style = null;//FJRF - Le quietamos el estilo al objeto para poder manipular el foco 
            cmbProceso.Style = null;//FJRF - Le quietamos el estilo al objeto para poder manipular el foco 

            cmbEmpleadoCodigo.Style = null;//FJRF - Le quietamos el estilo al objeto para poder manipular el foco 
            cmbEmpleado.Style = null;//FJRF - Le quietamos el estilo al objeto para poder manipular el foco 

            txtSemana.Focus();//FJRF - Ponemos el foco en semana
        }

        private void dtgNovedades_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            #region FJRF - Saber Fila y Columna indexada

            int IntColumnaIndexada, IntFilaIndexada;
            DependencyObject dep = (DependencyObject)e.OriginalSource;

            //Stepping through the visual tree
            while ((dep != null) && !(dep is System.Windows.Controls.DataGridCell))
            {
                dep = VisualTreeHelper.GetParent(dep);
            }

            //Is the dep a cell or outside the bounds of Window1?
            if (dep == null | !(dep is System.Windows.Controls.DataGridCell))
            {
                return;
            }
            else
            {
                System.Windows.Controls.DataGridCell cell = new System.Windows.Controls.DataGridCell();
                cell = (System.Windows.Controls.DataGridCell)dep;
                while ((dep != null) && !(dep is DataGridRow))
                {
                    dep = VisualTreeHelper.GetParent(dep);
                }

                if (dep == null)
                {
                    return;
                }
                int colindex = cell.Column.DisplayIndex;  //this returns COLUMN INDEX
                IntColumnaIndexada = colindex;

                DataGridRow row = dep as DataGridRow;
                System.Windows.Controls.DataGrid dataGrid = ItemsControl.ItemsControlFromItemContainer(row) as System.Windows.Controls.DataGrid;
                int rowindex = dataGrid.ItemContainerGenerator.IndexFromContainer(row); //this returns ROW INDEX

                IntFilaIndexada = rowindex;
            }
            #endregion

            int IntFilaActual, IntCantidadRegistros, IntRegistrosActuales;//FJRF Creamos las variables que necesitamos para el proceso actual

            IntCantidadRegistros = dtgNovedades.Items.Count;//FJRF - Traemos la cantidad de filas que tenga el grid

            IntFilaActual = IntFilaIndexada + 1;//FJRF - La fila actual es la fila indexada mas uno porque empieza en cero
            IntRegistrosActuales = IntCantidadRegistros - 1;//FJRF - Los registros actuales es la cantidad de filas menos una porque siempre debe de sobrar una

            var elemento = e.OriginalSource as UIElement;
            if (e.Key == Key.Enter && elemento != null)
            {
                e.Handled = true;
                elemento.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));

            }
        }

        //
        // SINGLE CLICK EDITING
        //
        private void DataGridCell_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            DataGridCell cell = sender as DataGridCell;
            if (cell != null && !cell.IsEditing && !cell.IsReadOnly)
            {
                if (!cell.IsFocused)
                {
                    cell.Focus();
                }
                DataGrid dataGrid = FindVisualParent<DataGrid>(cell);
                if (dataGrid != null)
                {
                    if (dataGrid.SelectionUnit != DataGridSelectionUnit.FullRow)
                    {
                        if (!cell.IsSelected)
                            cell.IsSelected = true;
                    }
                    else
                    {
                        DataGridRow row = FindVisualParent<DataGridRow>(cell);
                        if (row != null && !row.IsSelected)
                        {
                            row.IsSelected = true;
                        }
                    }
                }
            }
        }

        static T FindVisualParent<T>(UIElement element) where T : UIElement
        {
            UIElement parent = element;
            while (parent != null)
            {
                T correctlyTyped = parent as T;
                if (correctlyTyped != null)
                {
                    return correctlyTyped;
                }

                parent = VisualTreeHelper.GetParent(parent) as UIElement;
            }
            return null;
        }

        private void ventana_KeyDown(object sender, KeyEventArgs e)
        {
            var elemento = e.OriginalSource as UIElement;
            if (e.Key == Key.F3 && elemento != null)
            {
                if (MDOgeneral.logBusquedadAbierta == true) { MDOgeneral.logBusquedadAbierta = false; }
            }

            if (e.Key == Key.F4 && elemento != null)
            {
                if (MDOgeneral.logBusquedadAbierta1 == true) { MDOgeneral.logBusquedadAbierta1 = false; }
            }

            if (e.Key == Key.F5 && elemento != null)
            {
                if (MDOgeneral.logBusquedadAbierta2 == true) { MDOgeneral.logBusquedadAbierta2 = false; }
            }
        }

        #region FJRF - Control para el manejo de focos
        private void txtSemana_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)//FJRF - Si presionan la tecla enter hacemos lo siguiente
            {
                cmbProcesoCodigo.Focus();//FJRF - Ponemos el foco en este objeto
            }
        }
        private void cmbProcesoCodigo_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)//FJRF - Si presionan la tecla enter hacemos lo siguiente
            {
                cmbEmpleadoCodigo.Focus();//FJRF - Ponemos el foco en este objeto
            }
        }
        private void cmbProceso_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)//FJRF - Si presionan la tecla enter hacemos lo siguiente
            {
                cmbEmpleadoCodigo.Focus();//FJRF - Ponemos el foco en este objeto
            }
        }
        private void cmbEmpleadoCodigo_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)//FJRF - Si presionan la tecla enter hacemos lo siguiente
            {
                PttV_PasarFocoAlGridPrimeraColumna();//FJRF - Pasamos el foco
            }
        }
        private void cmbEmpleado_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)//FJRF - Si presionan la tecla enter hacemos lo siguiente
            {
                PttV_PasarFocoAlGridPrimeraColumna();//FJRF - Pasamos el foco                
            }
        }
        #endregion

        #region FJRF - FuncionesEspecialesParaLasPropiedadesDeLaCeldaYElFoco

        public static T FindVisualChild<T>(DependencyObject obj) where T : DependencyObject
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(obj, i);
                if (child != null && child is T)
                    return (T)child;
                else
                {
                    T childOfChild = FindVisualChild<T>(child);
                    if (childOfChild != null)
                        return childOfChild;
                }
            }
            return null;
        }
        public static DataGridCell GetCell(DataGrid dataGrid, DataGridRow rowContainer, int column)
        {
            if (rowContainer != null)
            {
                DataGridCellsPresenter presenter = FindVisualChild<DataGridCellsPresenter>(rowContainer);
                if (presenter == null)
                {
                    /* if the row has been virtualized away, call its ApplyTemplate() method 
                     * to build its visual tree in order for the DataGridCellsPresenter
                     * and the DataGridCells to be created */
                    rowContainer.ApplyTemplate();
                    presenter = FindVisualChild<DataGridCellsPresenter>(rowContainer);
                }
                if (presenter != null)
                {
                    DataGridCell cell = presenter.ItemContainerGenerator.ContainerFromIndex(column) as DataGridCell;
                    if (cell == null)
                    {
                        /* bring the column into view
                         * in case it has been virtualized away */
                        dataGrid.ScrollIntoView(rowContainer, dataGrid.Columns[column]);
                        cell = presenter.ItemContainerGenerator.ContainerFromIndex(column) as DataGridCell;
                    }
                    return cell;
                }
            }
            return null;
        }
        public static void SelectRowByIndexes(DataGrid dataGrid, params int[] rowIndexes)
        {
            if (!dataGrid.SelectionUnit.Equals(DataGridSelectionUnit.FullRow))
                throw new ArgumentException("The SelectionUnit of the DataGrid must be set to FullRow.");

            if (!dataGrid.SelectionMode.Equals(DataGridSelectionMode.Extended))
                throw new ArgumentException("The SelectionMode of the DataGrid must be set to Extended.");

            if (rowIndexes.Length.Equals(0) || rowIndexes.Length > dataGrid.Items.Count)
                throw new ArgumentException("Invalid number of indexes.");

            dataGrid.SelectedItems.Clear();
            foreach (int rowIndex in rowIndexes)
            {
                if (rowIndex < 0 || rowIndex > (dataGrid.Items.Count - 1))
                    throw new ArgumentException(string.Format("{0} is an invalid row index.", rowIndex));

                object item = dataGrid.Items[rowIndex]; //=Product X
                dataGrid.SelectedItems.Add(item);

                DataGridRow row = dataGrid.ItemContainerGenerator.ContainerFromIndex(rowIndex) as DataGridRow;
                if (row == null)
                {
                    dataGrid.ScrollIntoView(item);
                    row = dataGrid.ItemContainerGenerator.ContainerFromIndex(rowIndex) as DataGridRow;
                }
                if (row != null)
                {
                    DataGridCell cell = GetCell(dataGrid, row, 0);
                    if (cell != null)
                        cell.Focus();
                }
            }
        }
        public static void SelectCellByIndex(DataGrid dataGrid, int rowIndex, int columnIndex)
        {
            if (!dataGrid.SelectionUnit.Equals(DataGridSelectionUnit.Cell))
                throw new ArgumentException("The SelectionUnit of the DataGrid must be set to Cell.");

            if (rowIndex < 0 || rowIndex > (dataGrid.Items.Count - 1))
                throw new ArgumentException(string.Format("{0} is an invalid row index.", rowIndex));

            if (columnIndex < 0 || columnIndex > (dataGrid.Columns.Count - 1))
                throw new ArgumentException(string.Format("{0} is an invalid column index.", columnIndex));

            dataGrid.SelectedCells.Clear();

            object item = dataGrid.Items[rowIndex]; //=Product X
            DataGridRow row = dataGrid.ItemContainerGenerator.ContainerFromIndex(rowIndex) as DataGridRow;
            if (row == null)
            {
                dataGrid.ScrollIntoView(item);
                row = dataGrid.ItemContainerGenerator.ContainerFromIndex(rowIndex) as DataGridRow;
            }
            if (row != null)
            {
                DataGridCell cell = GetCell(dataGrid, row, columnIndex);
                if (cell != null)
                {
                    DataGridCellInfo dataGridCellInfo = new DataGridCellInfo(cell);
                    dataGrid.SelectedCells.Add(dataGridCellInfo);

                    cell.Focus();
                }
            }
        }
        #endregion

        protected void PttV_PasarFocoAlGridPrimeraColumna()
        {
            dtgNovedades.ScrollIntoView(dtgNovedades.Items[0], dtgNovedades.Columns[0]);
            dtgNovedades.CurrentCell = new DataGridCellInfo(dtgNovedades.Items[0], dtgNovedades.Columns[0]);//FJRF - Decimos en que fila y columna vamos a trabajar
            dtgNovedades.BeginEdit();//FJRF - Decimos que es para edicion
        }
        private void BtnGuardar_Click(object sender, RoutedEventArgs e)
        {
            cmbProcesoCodigo.Focus();
        }
    }
}
